package com.neusoft.nepa;

import com.neusoft.nepa.controller.*;
import com.neusoft.nepa.entity.*;
import com.neusoft.nepb.entity.Data;
import com.neusoft.nepb.entity.User;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.*;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class UserLogin extends Application {

    private Stage primaryStage;
    private static HashMap<String, Admin> AccountMap = new HashMap<>();
    private Admin currentUser;
    private static ArrayList<InfoUnit> infoUnits = new ArrayList<>();
    private HashMap<String, String[]> InfoCollect = new HashMap<>();
    private static List<Dept> depts = new ArrayList<>();
    private ArrayList<String> AdminKeys = new ArrayList<>();

    public void resetAccountMap(HashMap<String, Admin> NewAccountMap) throws IOException {

        for (String key : NewAccountMap.keySet()) {
            AccountMap.put(key, NewAccountMap.get(key));
        }
        resetAccountDat();
    }
    public void resetAccountDat() throws IOException {
        try (FileWriter writer = new FileWriter("src/com/neusoft/nepa/account_code.dat")) {
            System.out.println(" ");
        } catch (IOException e) {
            System.err.println(" " + e.getMessage());
        }
        for (String key : AccountMap.keySet()) {
            if (!AdminKeys.contains(AccountMap.get(key).getPhoneNumber())) {
                saveToFile(key);
            }
        }
        try (FileWriter writer = new FileWriter("user.txt")) {
            System.out.println(" ");
        } catch (IOException e) {
            System.err.println(" " + e.getMessage());
        }
        for (String key : AccountMap.keySet()) {
            Admin admin = AccountMap.get(key);
            if (!AdminKeys.contains(admin.getPhoneNumber())) {
                com.neusoft.nepb.entity.User u1 = new com.neusoft.nepb.entity.User(admin.getPhoneNumber(), admin.getName(), admin.getPassword(), admin.getSex());
                Map<String, com.neusoft.nepb.entity.User> userMap = com.neusoft.nepb.common.FileUtils.readMapObject("user.txt");
                userMap.put(u1.getPhoneNumber(), u1);
                com.neusoft.nepb.common.FileUtils.writeMapObject("user.txt", userMap);
            }
        }
    }
    private static void saveToFile(String key1) throws IOException {
        //AccountMap.get(name).get(password).get(phoneNumber).put(sex, age);

                        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/com/neusoft/nepa/account_code.dat",true))) {
                            String key2 = AccountMap.get(key1).getPassword();
                            String key3 = AccountMap.get(key1).getPhoneNumber();
                            String key4 = AccountMap.get(key1).getSex();
                            int key5 = AccountMap.get(key1).getAge();
                            String key6 = AccountMap.get(key1).getInfo();
                            bufferedWriter.write(key1 + "\t" + key2 + "\t" + key3 + "\t" + key4 + "\t" + key5 + "\t" + key6 + "\n");
                        }

    }
    private static void loadFromFile() throws IOException {
        //AccountMap.get(name).get(password).get(phoneNumber).put(sex, age); o
        File file = new File("src/com/neusoft/nepa/account_code.dat");
        if (!file.exists()) {
            boolean success = file.createNewFile();
            if (success) {
                System.out.println("Init");
            }
        }
        AccountMap.clear();
        try (Scanner scanner = new Scanner(new File("src/com/neusoft/nepa/account_code.dat"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] keys = line.split("\t");
                if (keys.length >= 5) {
                    String key6;
                    if (keys.length == 6) {
                        key6 = keys[5];
                    } else {
                        key6 = "无备注";
                    }
                    for (int i = 0; i <= 5; i++) {
                        UserInput(keys[0], keys[2], keys[1], keys[3], Integer.parseInt(keys[4]), key6);
                    }
                }
            }
        }
    }
    private static void UserInput(String name, String phoneNumber, String password, String sex, int age, String info) throws IOException {
        Admin user = new Admin(name, password, phoneNumber, sex, age);
        user.setInfo(info);
        AccountMap.put(name, user);
    }
    private void DeptInput(Dept dept) throws IOException {
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/com/neusoft/nepa/depts.dat", true))) {
            bufferedWriter.write(dept.toString());
        }
    }
    private FXMLLoader sceneSwap(URL url) throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(url);
        AnchorPane loginView = loader.load();
        Scene scene = new Scene(loginView);
        this.primaryStage.setScene(scene);
        return loader;
    }
    @Override
    public void start(Stage primaryStage) throws IOException {
        InfoNepbToNepa();
        loadFromFile();
        setAdminKeys();
        NepbToNepa();
        //InfoCommit("辽宁省","沈阳市","河流存在严重的工业污染，推断为食品加工厂超量排放。","134","宋南槿","2025年6月16日");
        //InfoCommit("河北省","衡水市","通过对大气环境检测，发现存在SO2, CO2严重超标排放问题，推测为化工厂排放导致。","240","宋南槿","2025年6月15日");
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("用户认证系统");
        primaryStage.setWidth(800);
        primaryStage.setHeight(600);

        FXMLLoader loader = new FXMLLoader();
        URL url = getClass().getResource("/com/neusoft/nepa/view/LoginView.fxml");
        loader.setLocation(url);
        AnchorPane rootLayout = loader.load();
        VukenAdminLoginViewController controller = loader.getController();
        controller.setMainApp(this);
        Scene scene = new Scene(rootLayout);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
    public static void main(String[] args) throws IOException {
        launch(args);
    }
    public static boolean includeStates(String name, String phoneNumber, String password, String sex, int age) throws IOException {
        if (AccountMap.containsKey(name)) {

            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle(null);
            alert.setHeaderText(null);


            Text contentText = new Text("\n\n用户已存在");
            alertHint(alert, contentText);

            return false;
        } else {
            String key6 = "无备注";
            UserInput(name, phoneNumber, password, sex, age, key6);
            saveToFile(name);

            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle(null);
            alert.setHeaderText(null);


            Text contentText = new Text("\n\n注册成功");
            contentText.setFill(Color.PURPLE);
            contentText.setFont(Font.font("Arial", FontWeight.BOLD, contentText.getFont().getSize()));
            alert.getDialogPane().setContent(contentText);
            alert.showAndWait();
            saveToFile(name);
            new Thread(() -> {
                try {
                    Thread.sleep(2000);
                    Platform.runLater(alert::close);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();

            return true;
        }
    }
    private static void alertHint(Alert alert, Text contentText) {
        contentText.setFill(Color.PURPLE);
        contentText.setFont(Font.font("Arial", FontWeight.BOLD, contentText.getFont().getSize()));
        alert.getDialogPane().setContent(contentText);
        alert.showAndWait();
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                Platform.runLater(alert::close);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
    public void showColorMap() throws IOException {
        URL url = getClass().getResource("/com/neusoft/nepa/view/ColorMap.fxml");
        FXMLLoader loader = sceneSwap(url);
        primaryStage.setTitle("中国空气质量地图");
        // 获取控制器并设置主应用引用
        ColorMapController controller = loader.getController();
        controller.setMainApp(this);

    }
    public HashMap<String, String[]> InfoArrange() throws IOException {
        InfoCollect.clear();
        File file = new File("src/com/neusoft/nepa/data_list.dat");
        if (!file.exists()) {
            boolean success = file.createNewFile();
            if (success) {
                System.out.println("Init");
            }
        }

        try (Scanner scanner = new Scanner(new File("src/com/neusoft/nepa/data_list.dat"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (line.equals("BEGIN")) {
                    String[] baseDataCollect = scanner.nextLine().split(" ");
                    String province = baseDataCollect[0].replace("省", "").split("_")[0];
                    if (!InfoCollect.containsKey(province)) {
                        InfoCollect.put(province, new String[]{"0", "0", "abc"});

                    }
                    ArrayList<String> temp = new ArrayList<>();
                    temp.add("一");
                    temp.add("二");
                    temp.add("三");
                    temp.add("四");
                    temp.add("五");
                    temp.add("六");
                    if (!temp.contains(baseDataCollect[2])) {
                        InfoCollect.get(province)[0] = (Integer.parseInt(InfoCollect.get(province)[0]) + 1) + "";
                        InfoCollect.get(province)[1] = (Integer.parseInt(InfoCollect.get(province)[1]) + Integer.parseInt(baseDataCollect[2])) + "";
                    }
                    StringBuilder sb = new StringBuilder();
                    sb.append("\n");
                    while (true) {
                        String info = scanner.nextLine();
                        if (info.equals("END")) {
                            break;
                        } else {
                            sb.append(info).append("\n");
                        }
                    }
                    sb.append("(").append(baseDataCollect[4]).append("提交于").append(baseDataCollect[3]).append(")").append("\n");
                    InfoCollect.get(province)[2] = sb.toString();
                }
            }
        }
        System.out.println(InfoCollect);
        return InfoCollect;
    }
    public List<Dept> DeptLoad() throws IOException {
        File file = new File("src/com/neusoft/nepa/depts.dat");
        if (!file.exists()) {
            boolean success = file.createNewFile();
            if (success) {
                System.out.println("Init");
            }
        }
        depts.clear();
        try (Scanner scanner = new Scanner(new File("src/com/neusoft/nepa/depts.dat"))) {
            while (scanner.hasNextLine()) {
                String[] line = scanner.nextLine().split("\t");
                if (line.length == 3) {
                    Dept dept = new Dept(line[0], line[1], line[2]);
                    depts.add(dept);
                }
            }
        }
        System.out.println("---------\n" + depts + "\n" + "---------\n");
        return depts;
    }
    public void showAdminView() throws IOException {
        URL url = getClass().getResource("/com/neusoft/nepa/view/VukenAdminView.fxml");
        FXMLLoader loader = sceneSwap(url);
        // 获取控制器并设置主应用引用
        VukenAdminViewController controller = loader.getController();
        controller.setMainApp(this);

    }
    public HashMap<String, Admin> getUserMap() throws IOException {
        loadFromFile();
        setAdminKeys();
        NepbToNepa();
        return AccountMap;
    }
    public void showUserManageView() throws IOException {
        URL url = getClass().getResource("/com/neusoft/nepa/view/AdminManageView.fxml");
        FXMLLoader loader = sceneSwap(url);
        // 获取控制器并设置主应用引用
        AdminManageController controller = loader.getController();
        controller.setMainApp(this);

    }
    public void showDeptManageView() throws IOException {
        URL url = getClass().getResource("/com/neusoft/nepa/view/DeptManagerView.fxml");
        FXMLLoader loader = sceneSwap(url);
        // 获取控制器并设置主应用引用
        DeptManagerViewController controller = loader.getController();
        controller.setMainApp(this);

    }
    public HashMap<String, Admin> deleteUser() throws IOException {

        return getUserMap();
    }
    public void FormNotCorrect() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(null);
        alert.setHeaderText(null);


        Text contentText = new Text("\n\n格式错误或存在空缺");
        alertHint(alert, contentText);
    }
    public void loginDetect(String name, String password) throws IOException {
        if (AccountMap.containsKey(name) && AdminKeys.contains(AccountMap.get(name).getPhoneNumber())) {
            if (AccountMap.get(name).getPassword().equals(password)) {

                showAdminView();

            } else {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle(null);
                alert.setHeaderText(null);


                Text contentText = new Text("\n\n密码错误");
                alertHint(alert, contentText);
            }
        } else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle(null);
            alert.setHeaderText(null);


            Text contentText = new Text("\n\n无此管理员");
            alertHint(alert, contentText);
        }
    }
    public void showLoginView() throws IOException {
        URL url = getClass().getResource("/com/neusoft/nepa/view/LoginView.fxml");
        FXMLLoader loader = sceneSwap(url);
        // 获取控制器并设置主应用引用
        VukenAdminLoginViewController controller = loader.getController();
        controller.setMainApp(this);

    }
    public void showRegisterView() throws IOException {
        // 加载注册视图
        URL url = getClass().getResource("/com/neusoft/nepa/view/RegisterView.fxml");
        FXMLLoader loader = sceneSwap(url);
        // 获取控制器并设置主应用引用
        VukenAdminRegisterViewController controller = loader.getController();
        controller.setMainApp(this);
    }
    public void PhoneNumberFormNotCorrect() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(null);
        alert.setHeaderText(null);


        Text contentText = new Text("\n\n不存在此密钥！");
        alertHint(alert, contentText);
    }
    public static void InfoCommit(String province, String district, String info, String level, String name, String formattedDateTime) throws IOException {
//
        //LocalDateTime currentDateTime = LocalDateTime.now();
        //DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        //String formattedDateTime = currentDateTime.format(formatter);
//
        InfoUnit infoUnit = new InfoUnit(province, district, level, formattedDateTime, name, info);
        infoUnits.add(infoUnit);

        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/com/neusoft/nepa/data_list.dat", true))) {
            bufferedWriter.write(infoUnit.toString());
        }


    }
    private static void NepbToNepa() {
        Map<String, com.neusoft.nepb.entity.User> userMap = FileUtils.readMapObject("user.txt");
        for (com.neusoft.nepb.entity.User user : userMap.values()) {
            AccountMap.put(user.getUserName(), new Admin(user.getUserName(), user.getPassword(), user.getPhoneNumber(), user.getgender(), 1));
        }
    }
    public ArrayList<String> getAdminKeys() {
        return AdminKeys;
    }
    private void setAdminKeys() {
        AdminKeys.clear();
        AdminKeys.add("anonchihaya");
    }
    public void resetDeptList(ArrayList<Dept> returnDeptList) throws IOException {
        depts.clear();
        depts.addAll(returnDeptList);
        resetDeptDat();
    }
    public void resetDeptDat() throws IOException {
        try (FileWriter writer = new FileWriter("src/com/neusoft/nepa/depts.dat")) {
            System.out.println(" ");
        } catch (IOException e) {
            System.err.println(" " + e.getMessage());
        }
        for (Dept dept : depts) {
            DeptInput(dept);
        }
    }
    public static HashMap<String,String[]> deptAccountToNepc() throws FileNotFoundException {
        HashMap<String,String[]> deptAccountToNepc = new HashMap<>();
        try (Scanner scanner = new Scanner(new File("src/com/neusoft/nepa/depts.dat"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] keys = line.split("\t");
                if (keys.length == 3) {
                    deptAccountToNepc.put(keys[1], new String[]{keys[2], keys[0].split("市")[0]+"市",keys[0].split("市")[1]});
                }
            }
        }
        return deptAccountToNepc;
    }
    //return HashMap<name,String[]{password, address}>
    //for nepc method: HashMap<String, String[]> userMap = UserLogin.deptAccountToNepc();
    private static void InfoNepbToNepa() throws IOException {
        //
        File file = new File("finalMap.txt");
        Map<Date, Data> infoList = null;
        try{
            if(file.length()==0) {
                infoList = new HashMap<>();
            }
            else{
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                infoList = (Map) ois.readObject();
            }
        } catch(IOException | ClassNotFoundException e){
            throw new RuntimeException(e);
        }

        try (FileWriter writer = new FileWriter("finalMap.txt")) {
            System.out.println(" ");
        } catch (IOException e) {
            System.err.println(" " + e.getMessage());
        }

        for (Data info : infoList.values()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
            String formattedDate = sdf.format(info.getTime());
            InfoCommit(info.getProvince(),info.getDistrict(),info.getInfo(),info.getDegree(),info.getDetailAddress()+"一位监督员",formattedDate);
        }
    }
    public static List<String[]> getInfo() throws IOException {
        InfoNepbToNepa();
        List<String[]> infoList = new ArrayList<>();
        File file = new File("src/com/neusoft/nepa/data_list.dat");
        if (!file.exists()) {
            boolean success = file.createNewFile();
            if (success) {
                System.out.println("Init");
            }
        }
        try (Scanner scanner = new Scanner(new File("src/com/neusoft/nepa/data_list.dat"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (line.equals("BEGIN")) {
                    String[] unitInfo = {"","","","","","",""};
                    String[] baseDataCollect = scanner.nextLine().split(" ");
                    String province = baseDataCollect[0].replace("省", "");
                    //if (!InfoCollect.containsKey(province)) {
                    //    InfoCollect.put(province, new String[]{"0", "0", "abc"});
                    //}
                    //province city aqi time detailed_time name info
                    unitInfo[0] = province.split("_")[0];
                    unitInfo[1] = baseDataCollect[1];
                    unitInfo[2] = baseDataCollect[2];
                    String[] unitInfoTemp = baseDataCollect[3].split("日");
                    unitInfo[3] = unitInfoTemp[0]+"日";
                        unitInfo[4] = unitInfoTemp[1];
                    unitInfo[5] = baseDataCollect[4];
                    StringBuilder sb = new StringBuilder();
                    sb.append("\n");
                    while (true) {
                        String info = scanner.nextLine();
                        if (info.equals("END")) {

                            break;
                        } else {
                            sb.append(info).append("\n");
                        }
                    }
                    unitInfo[6] = sb.toString();
                    infoList.add(unitInfo);
                }
            }
        }
        return infoList;
    }
    public boolean updateDataListAQILevel(String province, String city, int aqiIndex, String new_province_tool) throws IOException {
        List<String> lines = new ArrayList<>();
        File file = new File("src/com/neusoft/nepa/data_list.dat");

        // 读取文件内容
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        }

        // 查找并修改特定报告地的污染等级
        boolean found = false;
        for (int i = 0; i < lines.size(); i++) {
            if (lines.get(i).trim().equals("BEGIN")) {
                // 找到 BEGIN 标记，检查下一行是否匹配报告地
                if (i + 1 < lines.size()) {
                    String dataLine = lines.get(i + 1);
                    String[] parts = dataLine.trim().split("\\s+"); // 按空格分割

                    // 检查是否包含足够的部分，并且前两部分匹配省和市
                    if (parts.length >= 3 && parts[0].equals(province) && parts[1].equals(city)) {
                        // 直接替换第三部分（污染等级）为 AQI 指数
                        parts[2] = String.valueOf(aqiIndex);
                        parts[0] = new_province_tool;
                        lines.set(i + 1, String.join(" ", parts));
                        found = true;
                        break;
                    }
                }
            }
        }

        if (!found) {
            System.out.println("警告：未找到报告地 '" + province + " " + city + "' 的记录！");
        }

        // 写入修改后的数据
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
            for (String line : lines) {
                bw.write(line);
                bw.newLine();
            }
        }
        return found;
    }
    public HashMap<String, ArrayList<AdminDataDTO>> getArrangedData() {
        return (HashMap<String, ArrayList<AdminDataDTO>>) FileUtils.readMapObject("src/com/neusoft/nepa/arrange_list.txt");
    }
    // so2 co pm25
    public ArrayList<ProvinceProblem> ProvinceListDetect() throws FileNotFoundException {
        HashMap<String,int[]> map = new HashMap<>();
        try (Scanner scanner = new Scanner(new File("src/com/neusoft/nepa/data_list.dat"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().split(" ")[0];
                if (line.contains("_")&&line.split("_").length==5) {
                    String[] temp = line.split("_");
                    if (!map.containsKey(temp[0])) {
                        map.put(temp[0], new int[]{Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4])});
                    } else {
                        int[] temp2 = map.get(temp[0]);
                        for (int i = 0; i < 4; i++) {
                            temp2[i] += Integer.parseInt(temp[i+1]);
                        }
                        map.put(temp[0], temp2);
                    }
                }
            }
        }
        ArrayList<ProvinceProblem> provinceList = new ArrayList<>();
        for (String key : map.keySet()) {
            provinceList.add(new ProvinceProblem(key,map.get(key)[0],map.get(key)[1],map.get(key)[2],map.get(key)[3]));
        }
        return provinceList;
    }
}
